package io.nio;

import framework.AbstractTest;
import utils.Log;
import utils.StringUtils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * Created by shane on 2018/5/20.
 *
 * nio的目标就是快速移动大量数据， 因此ByteBuffer的大小就显得尤为重要
 */
public class BufferToText extends AbstractTest {
    protected static final String TAG = BufferToText.class.getName();

    @Override
    public void test(String[] args) {
        super.test(args);

        String tempPath = getDefTempFile(args);

        try {
            FileChannel fc = new FileOutputStream(tempPath).getChannel();
            fc.write(ByteBuffer.wrap("some data...".getBytes()));
            fc.close();

            ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
            fc = new FileInputStream(tempPath).getChannel();
            fc.read(buffer);
            buffer.flip();
            // Doesn't work
            Log.v(buffer.asCharBuffer());

            // Decode using this system's default Charset
            buffer.rewind();
            String encoding = System.getProperty(FILE_ENCODING);
            Log.v(StringUtils.getAppendString("Decode using ", encoding, ": ",
                    Charset.forName(encoding).decode(buffer).toString()));

            fc = new FileOutputStream(tempPath).getChannel();
            fc.write(ByteBuffer.wrap("some data...".getBytes(TEXT_ENCODING_UTF16BE)));
            fc.close();
            // now try reading again
            fc = new FileInputStream(tempPath).getChannel();
            buffer.clear();
            fc.read(buffer);
            buffer.flip();
            Log.v(buffer.asCharBuffer());

            // Use a CharBuffer to write through
            fc = new FileOutputStream(tempPath).getChannel();
            buffer = ByteBuffer.allocate(24);
            buffer.asCharBuffer().put("some text");
            fc.write(buffer);
            fc.close();

            // Read and display
            fc = new FileInputStream(tempPath).getChannel();
            buffer.clear();
            fc.read(buffer);
            buffer.flip();
            Log.v(buffer.asCharBuffer());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String getTag() {
        return TAG;
    }

}
